package be.android.forap.dataprovider;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import org.spongycastle.jce.provider.BouncyCastleProvider;

import be.android.forap.crypto.CryptoUtil;

import android.util.Log;

public class ContactIntegrityElement {

	private long mId;
	private String globalcontactId;

	private byte[] contactDigest;

	public ContactIntegrityElement(long id, String globalcId, byte[] cDigest){
		mId = id;
		globalcontactId = globalcId;
		contactDigest = cDigest;
	}

	public boolean verifyIntegrity(RawContact contact){
		return contact.verify(contactDigest);
		/*try {
			String sensitiveData = contact.getGlobalContactId()+contact.getPublicKeyBlock();
			Log.i("ADD",sensitiveData);
			Security.addProvider(new BouncyCastleProvider());
			MessageDigest md;
			md = MessageDigest.getInstance("SHA-512", "SC");
			byte [] digest = md.digest(sensitiveData.getBytes());
			return (MessageDigest.isEqual(digest,contactDigest));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}*/
	}

	public boolean verifyIntegrity(String globalId, String pubKey){
		try {
			String sensitiveData = globalcontactId+pubKey;
			Log.i("DIGEST COMPARE1",sensitiveData);
			Security.addProvider(new BouncyCastleProvider());
			MessageDigest md;
			md = MessageDigest.getInstance("SHA-512", "SC");
			byte [] digest = md.digest(sensitiveData.getBytes());
			Log.i("DIGEST COMPARE1",CryptoUtil.toHex(contactDigest));
			Log.i("DIGEST COMPARE2",CryptoUtil.toHex(digest));
			Log.i("DIGEST COMPARETest",""+MessageDigest.isEqual(digest,contactDigest));
			return (MessageDigest.isEqual(digest,contactDigest));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	protected long getId() {
		return mId;
	}

	protected String getGlobalcontactId() {
		return globalcontactId;
	}

	protected byte[] getContactDigest() {
		return contactDigest;
	}
}
